package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.UploadObjectArgs;
import lombok.SneakyThrows;
import lombok.Synchronized;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Autowired
    MinioClient minioClient;
    @Autowired
    MinioProperties minioProperties;

    @SneakyThrows//不抛出异常
    @Override
    public String upload(MultipartFile file) {
        InputStream inputStream = file.getInputStream();

        String timePath = DateTime.now().toString("/yyyy/MM/dd/");
        String fileName = UUID.randomUUID().toString().replace("-", "") + file.getOriginalFilename();
String objectName = timePath + fileName;
        PutObjectArgs build = PutObjectArgs.builder()
                .stream(inputStream, file.getSize(), -1)
                .bucket(minioProperties.getBucketName())
                .object(objectName)
                .build();
        minioClient.putObject(build);

        String url = minioProperties.getEndpoint() +"/" + minioProperties.getBucketName() + objectName;
        System.out.println(url);
        return url;
    }
}
